package cn.lblbc.todo

import android.content.Context
import cn.lblbc.todo.db.TodoDatabase
import cn.lblbc.todo.repository.TaskRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

object TaskManager {
    private lateinit var repository: TaskRepository
    private val coroutineScope = CoroutineScope(Dispatchers.IO)
    
    fun init(context: Context) {
        val database = TodoDatabase.getDatabase(context)
        repository = TaskRepository(database.taskDao())
    }
    
    fun getAllTasks(): Flow<List<Task>> = repository.getAllTasks()
    
    fun getActiveTasks(): Flow<List<Task>> = repository.getActiveTasks()
    
    fun getCompletedTasks(): Flow<List<Task>> = repository.getCompletedTasks()
    
    fun addTask(task: Task) {
        coroutineScope.launch {
            repository.insertTask(task)
        }
    }
    
    fun updateTask(task: Task) {
        coroutineScope.launch {
            repository.updateTask(task)
        }
    }
    
    fun deleteTask(taskId: Long) {
        coroutineScope.launch {
            repository.deleteTaskById(taskId)
        }
    }
}